package com.example.Controller;

import com.example.Mapper.UserMapper;
import com.example.pojo.Result;
import com.example.pojo.User;
import jakarta.annotation.Resource;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

@RestController
@Slf4j
public class UserController {
    @Resource
    private UserMapper userMapper;
    @PostMapping("/login")
    @ResponseBody
    public Result login(String username, String password, HttpServletRequest request) {
        User user = userMapper.selectByUserName(username);
//        System.out.println("登录用户:"+user);
        if (user == null||!user.getPassword().equals(password)) {
            return Result.error("登录失败,用户名或密码错误!");
        }
        HttpSession session = request.getSession(true);
        session.setAttribute("user", user);
        user.setPassword(null);
        return Result.success(user);
    }
    @PostMapping("/register")
    @ResponseBody
    public Result register(String username, String password) {
       User Registeruser = userMapper.selectByUserName(username);
       if (Registeruser != null) {
           return Result.error("用户名已被注册");
       }
       User user = new User();
       user.setUsername(username);
       user.setPassword(password);
       userMapper.insertUser(user);
       return Result.success();
   }
   @GetMapping("/userInfo")
   @ResponseBody
   public Result getUserInfo(HttpServletRequest request) {
        HttpSession session = request.getSession(false);
        if (session == null) {
            return Result.error("用户未登录");
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            return Result.error("获取的user对象为空");
        }
        user.setPassword(null);
        return Result.success(user);
    }
}
